//
//  HYStoreViewController.m
//  HaiYue
//
//  Created by skyline on 2018/6/14.
//  Copyright © 2018年 skyline. All rights reserved.
//

#import "HYStoreViewController.h"
#import "HYGoodsViewController.h"
#import "HYStoreCell.h"
#import "HYStoreListModel.h"
#import "HYGoodsModel.h"
#import "HYStoreListOrder.h"

CGFloat const HYSTOREHEADERHEIGHT = 25;
@interface HYStoreViewController ()<UICollectionViewDelegate,UICollectionViewDataSource>
@property (nonatomic, strong) UISegmentedControl *seg;
@property (nonatomic, strong) UICollectionView *collectionView;
@property (nonatomic, strong) HYStoreListModel *model;
@property (nonatomic, strong) NSArray *list;
@end

@implementation HYStoreViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    self.title = @"巅峰商城";
    // Do any additional setup after loading the view.
}

- (UISegmentedControl *)seg
{
    if (!_seg)
    {
        _seg = [[UISegmentedControl alloc] initWithItems:@[@"等级:vip0",@"积分:0",@"兑换券记录"]];
        _seg.tintColor = THEME_COLOR;
        _seg.selectedSegmentIndex = 1;
        [_seg addTarget:self action:@selector(actionForStoreSeg:) forControlEvents:UIControlEventValueChanged];
        [self.view addSubview:_seg];
        [_seg mas_makeConstraints:^(MASConstraintMaker *make) {
            make.top.equalTo(self.view);
            make.left.equalTo(self.view);
            make.right.equalTo(self.view);
            make.height.mas_offset(44);
        }];
    }
    return _seg;
}

- (UICollectionView *)collectionView
{
    if (!_collectionView)
    {
        _collectionView = [[UICollectionView alloc] initWithFrame:CGRectZero collectionViewLayout:[self flowLayout]];
        _collectionView.delegate = self;
        _collectionView.dataSource = self;
        _collectionView.bounces = NO;
        _collectionView.showsHorizontalScrollIndicator = NO;
        _collectionView.backgroundColor = [UIColor whiteColor];
        [_collectionView registerClass:[HYStoreCell class] forCellWithReuseIdentifier:@"HYStoreCell"];
        [_collectionView registerClass:[UICollectionReusableView class] forSupplementaryViewOfKind:UICollectionElementKindSectionHeader withReuseIdentifier:@"HYStoreCellHeader"];
        _collectionView.mj_header = [MJRefreshHeader headerWithRefreshingTarget:self refreshingAction:@selector(actionForStoresNew:)];
        _collectionView.mj_footer = [MJRefreshFooter footerWithRefreshingTarget:self refreshingAction:@selector(actionForStoresMore:)];
        [self.view addSubview:_collectionView];
        [_collectionView mas_makeConstraints:^(MASConstraintMaker *make) {
            make.top.equalTo(self.seg.mas_bottom).with.offset(1);
            make.left.equalTo(self.view);
            make.right.equalTo(self.view);
            make.bottom.equalTo(self.view);
        }];
    }
    return _collectionView;
}

- (UICollectionViewFlowLayout *)flowLayout
{
    UICollectionViewFlowLayout * layout = [[UICollectionViewFlowLayout alloc] init];
    layout.itemSize = CGSizeMake((SCREEN_WIDTH - GAP * 3.0) / 2.0, (SCREEN_WIDTH - GAP * 3.0) / 2.0);
    layout.headerReferenceSize = CGSizeMake(SCREEN_WIDTH, HYSTOREHEADERHEIGHT);
    layout.sectionInset = UIEdgeInsetsMake(GAP, GAP, GAP, GAP);
    layout.scrollDirection = UICollectionViewScrollDirectionVertical;
    return layout;
}

- (HYStoreListModel *)model
{
    if (!_model)
    {
        _model = [CCSave unarchiverObjFromFile:STORE_MODEL];
    }
    return _model;
}

- (NSArray *)list
{
    if (!_list || [_list count] < 1)
    {
       NSDictionary *dict = [self.model mj_keyValues];
       _list = [[HYStoreListOrder order:dict] valueForKey:@"list"];
    }
    return _list;
}

- (void)actionForStoreSeg:(UISegmentedControl *)sender
{
    Class vc;
    if (sender.selectedSegmentIndex == 0)
    {
        vc = NSClassFromString(@"HYLevelViewController");
    }
    else if (sender.selectedSegmentIndex == 1)
    {
        sender.selectedSegmentIndex = -1;
    }
    else
    {
        vc = NSClassFromString(@"HYExchangeViewController");
    }
    [self.navigationController pushViewController:[vc new] animated:YES];
}

- (void)actionForStoresNew:(MJRefreshHeader *)header
{
//    [self httpRequest];
    [self.collectionView.mj_header endRefreshing];

}

- (void)actionForStoresMore:(MJRefreshFooter *)footer
{
    [footer beginRefreshing];
//    [self httpRequest];
    [self.collectionView.mj_footer endRefreshing];
}

- (void)httpRequest
{
    [self startHUD];
    [CCHttp post:API_SHOP_LIST para:nil success:^(id  _Nonnull response) {
        [self endHUD];
        //        [self.collectionView.mj_header endRefreshing];
        //        [self.collectionView.mj_footer endRefreshing];
        self.model = [HYStoreListModel mj_objectWithKeyValues:response];
        if (self.model.retcode == 100)
        {
            [self.collectionView reloadData];
            [CCSave archiver:self.model toFile:STORE_MODEL];
        }
    } fail:^(NSError * _Nonnull error) {
        [self endHUD];
    }];
}
#pragma mark - UICollectionViewDataSource
- (NSInteger)numberOfSectionsInCollectionView:(UICollectionView *)collectionView
{
    return self.list.count;
}

- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section
{
    NSDictionary *vipLV = self.list[section];
    NSArray *goods = [[vipLV allValues] firstObject];
    return goods.count;
}

- (__kindof UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath
{
    NSDictionary *vipLV = self.list[indexPath.section];
    NSArray *goodsmodels = [[vipLV allValues] firstObject];
    HYStoreCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"HYStoreCell" forIndexPath:indexPath];
    if (!cell)
    {
        cell = [[HYStoreCell alloc] init];
    }
    cell.model = goodsmodels[indexPath.row];;
    return cell;
}

#pragma mark - UICollectionViewDelegate
- (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath
{
   HYStoreCell *cell = (HYStoreCell *)[collectionView cellForItemAtIndexPath:indexPath];
   HYGoodsViewController *vc = [[HYGoodsViewController alloc] init];
    vc.goodsid = cell.model.goodsid;
    [self.navigationController pushViewController:vc animated:YES];
}

- (UICollectionReusableView *)collectionView:(UICollectionView *)collectionView viewForSupplementaryElementOfKind:(NSString *)kind atIndexPath:(NSIndexPath *)indexPath
{
    if (kind == UICollectionElementKindSectionHeader)
    {
        UICollectionReusableView *headerView = [collectionView dequeueReusableSupplementaryViewOfKind:kind withReuseIdentifier:@"HYStoreCellHeader" forIndexPath:indexPath];
        headerView.backgroundColor = [UIColor clearColor];
        
        [headerView.subviews enumerateObjectsUsingBlock:^(__kindof UIView * _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
            [obj removeFromSuperview];
            obj = nil;
        }];
        
        HYFillLabel *label = [[HYFillLabel alloc]initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH / 2.0 - 1.5 * GAP, 25) typeOfshapeLayer:CCShapeLayerTypeRightHalfEllipse attribute:@{HYTextColor:ORANGE_COLOR,HYTextFont:[UIFont systemFontOfSize:13],HYBorderColor:THEME_COLOR,HYLayerColor:BLUE_COLOR}];
        
        label.text = [NSString stringWithFormat:@"VIP%@兑换区",[[self.list[indexPath.section] allKeys] firstObject]];
        [headerView addSubview:label];
        [label mas_makeConstraints:^(MASConstraintMaker *make) {
            make.left.equalTo(headerView);
            make.centerY.equalTo(headerView);
            make.size.mas_offset(label.bounds.size);
        }];
        return headerView;
    }
    else if (kind == UICollectionElementKindSectionFooter)
    {
        
    }
    return nil;
}


- (void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
    self.style = HYViewNaviBarStyleOnlyLeftBtn;
    self.seg.hidden = NO;
    [self httpRequest];
    
//    [[CCDB db] select:@"store" withOptions:nil conditionsDict:@{@"tag":@"/1.png"} complete:^(NSMutableArray * _Nonnull array) {
//        for (NSDictionary *dict in array)
//        {
//            
//        }
//    }];
}

- (void)viewDidAppear:(BOOL)animated
{
    [super viewDidAppear:animated];
    self.seg.selectedSegmentIndex = -1;
}
- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
 #pragma mark - Navigation
 
 // In a storyboard-based application, you will often want to do a little preparation before navigation
 - (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
 // Get the new view controller using [segue destinationViewController].
 // Pass the selected object to the new view controller.
 }
 */

@end
